package com.geese.module.ceo.service;

import java.util.List;
import java.util.Objects;

import com.geese.exception.BusinessException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.geese.common.entity.Campus;
import com.geese.common.entity.School;
import com.geese.common.util.PageUtil;
import com.geese.common.vo.Page;
import com.geese.common.vo.Paginator;
import com.geese.module.ceo.dao.BuildingMapper;
import com.geese.module.ceo.dao.CampusMapper;
import com.geese.module.ceo.dao.SchoolMapper;
import com.github.pagehelper.PageHelper;

/**
 * @author YeFangYi 
 */
@Service
public class CampusService {
	
	@Autowired
	private CampusMapper campusMapper;
	@Autowired
	private BuildingMapper buildingMapper;
	@Autowired
	private SchoolMapper schoolMapper;
	

	/**
	 * 保存校区
	 */
	public void save(Campus campus) {
		Campus nameCampus = campusMapper.findByName(campus.getSchoolId(), campus.getName());
		if(nameCampus != null) {
			throw new BusinessException(120043);
		}
		campus.setDisplayable(1);
		campus.setEnable(1);
		campusMapper.save(campus);
	}

	/**
	 * 修改校区
	 */
	public void update(Campus campus) {
		Campus model = campusMapper.findById(campus.getId());
		if(model == null) {
			throw new BusinessException(120039);
		}
		Campus nameCampus = campusMapper.findByName(model.getSchoolId(), campus.getName());
		if(nameCampus != null && !Objects.equals(model.getId(), nameCampus.getId())) {
			throw new BusinessException(120043);
		}
		model.setName(campus.getName());
		campusMapper.update(model);
	}

	/**
	 * 批量删除校区
	 */
	public void batchRemove(List<Integer> campusIds) {
		List<Campus> campusList = campusMapper.listByIds(campusIds);
		if (CollectionUtils.isEmpty(campusList) || campusList.size() != campusList.size()) {
			throw new BusinessException(120039);
		}
		campusMapper.batchRemoveByIds(campusIds);
		buildingMapper.batchRemoveByCampusIds(campusIds);
	}
	
	/**
	 * 查询校区列表
	 */
	public Paginator<Campus> listAllByQuery(Integer schoolId, String name, Page page) {
		PageHelper.startPage(page.getCurrPage(), page.getPageSize(), " id DESC");
		List<Campus> campusList = campusMapper.listAllByQuery(schoolId, name);
		return PageUtil.getPage(campusList);
	}

	/**
	 * 获取学校下的全部校区
	 */
	public List<Campus> listAll(Integer schoolId) {
		School school = schoolMapper.findById(schoolId);
		if(school == null) {
			throw new BusinessException(120015);
		}
		return campusMapper.listAll(schoolId);
	}

}
